//logs.js
const util = require('../../utils/util.js')
const app = getApp()
const cfg = require("../../utils/config.js");
const utilMd5 = require('../../utils/MD5.js');
Page({
  data: {
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标  1表示显示  0表示不显示
      title: '登录', //导航栏 中间的标题
      white: true, // 是就显示白的，不是就显示黑的。
      address: '' // 加个背景 不加就是没有
    },
    height: app.globalData.height * 2 + 30,
    logIcon:'../../images/logo1-6.png',
    loginName:'',
    loginPsd:'',
    loginCode:'',
    codeIcon:'',
    codeDate:'',
    loginType:1,  // 登录类型，1 手机号快捷登录，2 账号密码登录
    loginPhone:'',    // 手机快捷登录手机号
    loginPhoneCode:'',   // 手机快捷登录验证码
    isCodeIng:false,//获取验证码状态，倒计时
    codeTxt:'获取验证码', //获取验证码
      codeDisabled: false, // 验证码按钮是否禁用

    //微信登录数据
    openid: "",
    loginstate: "0",
    userEntity: null,
    userInfo: '',
    terminal: "",
    osVersion: "",
    phoneNumber: "",
    showModal: false,   // 定义登录弹窗
  },
  onLoad: function () {
   
    var date = new Date().getTime();
    this.setData({
      logs: (wx.getStorageSync('logs') || []).map(log => {
        return util.formatTime(new Date(log))
      }),
      codeDate: date,
      codeIcon: cfg.requestURL + '/backend/agent/mobile/getVerifyCodeImage?key=' + date
    })
      //console.log(date, this.data.codeDate)
  },
    // 微信一键登录
  onGotUserInfo: function(e) {
      //console.log('onGotUserInfo-----------'+e.detail.errMsg)
    var that = this;
    if (e.detail.errMsg == "getUserInfo:ok") {
      wx.setStorage({
        data: e.detail.userInfo,
        key: 'userinfo'
      })
      this.setData({userInfo: e.detail.userInfo});
      that.showDialogBtn(); // 调用一键获取手机号弹窗
    }
  },
  // 显示一键获取手机号弹窗
  showDialogBtn: function() {
      //.log('showModal------'+this.data.showModal)
    this.setData({
      showModal: true //修改弹窗状态为true，即显示
    })
  },
  // 隐藏一键获取手机号弹窗
  hideModal: function() {
    this.setData({
      showModal: false  //修改弹窗状态为false,即隐藏
    })
  },
  onshow: function (openid, userInfo, phoneNumber) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({ terminal: res.model });
        that.setData({ osVersion: res.system });
      }
    })
    wx.request({
      url: '登录接口',
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      data: {
        username: phoneNumber,
        parentuser: 'xudeihai',
        wximg: userInfo.avatarUrl,
        nickname: userInfo.nickName,
        identity: "",
        terminal: that.data.terminal,
        osVersion: that.data.system,
        logintype: "10",//微信登录
        openid: that.data.openid,
      },
      success(res) {
        if (res.data.r == "T") {
          that.setData({ userEntity: res.data.d });
          wx.setStorage({
            key: "userEntity",
            data: res.data.d
          })
          that.setData({ loginstate: "1" });
          wx.setStorage({
            key: "loginstate",
            data: "1"
          })
          wx.setStorage({
            key: 'userinfo',
            data: "1"
          })
        }
        else {
          return;
        }
      },
      fail(res) {
          //console.log(res);
      }
    })
  },
  //绑定手机
  getPhoneNumber: function (e) {
    var that = this;
    that.hideModal();
    wx.checkSession({
      success: function () {
        wx.login({
          success: res => {
            wx.request({
              url: '自己的登录接口', //仅为示例，并非真实的接口地址
              data: {
                account: '1514382701',
                jscode: res.code
              },
              method: "POST",
              header: {
                'content-type': 'application/json' // 默认值
              },
              success(res) {
                if (res.data.r == "T") {
                  wx.setStorage({
                    key: "openid",
                    data: res.data.openid
                  })
                  wx.setStorage({
                    key: "sessionkey",
                    data: res.data.sessionkey
                  })
                  wx.setStorageSync("sessionkey", res.data.sessionkey);
                  wx.request({
                    url: '自己的解密接口',//自己的解密地址
                    data: {
                      encryptedData: e.detail.encryptedData,
                      iv: e.detail.iv,
                      code: wx.getStorageSync("sessionkey")
                    },
                    method: "post",
                    header: {
                      'content-type': 'application/json'
                    },
                    success: function (res) {
                      if (res.data.r == "T") {
                        that.onshow(that.data.openid, that.data.userInfo, res.data.d.phoneNumber);//调用onshow方法，并传递三个参数
                          //console.log("登录成功")
                          //console.log(res.data.d.phoneNumber)//成功后打印微信手机号
                      }
                      else {
                          //console.log(res);
                      }
                    }
                  })
                }
              }
            })
          }
        })
      },
      fail: function () {
        wx.login({
          success: res => {
            wx.request({
              url: '自己的登录接口', //仅为示例，并非真实的接口地址
              data: {
                account: '1514382701',
                jscode: res.code
              },
              method: "POST",
              header: {
                'content-type': 'application/json' // 默认值
              },
              success(res) {
                if (res.data.r == "T") {
                  wx.setStorage({
                    key: "openid",
                    data: res.data.openid
                  })
                  wx.setStorage({
                    key: "sessionkey",
                    data: res.data.sessionkey
                  })
                  wx.request({
                    url: '自己的解密接口',//自己的解密地址
                    data: {
                      encryptedData: e.detail.encryptedData,
                      iv: e.detail.iv,
                      code: res.data.sessionkey
                    },
                    method: "post",
                    header: {
                      'content-type': 'application/json'
                    },
                    success: function (res) {
                      that.onshow(that.data.openid, that.data.userInfo, res.data.d.phoneNumber);//调用onshow方法，并传递三个参数
                    }
                  })
                }
              }
            })
          }
        })
      }
    })
  },
    getPhoneCode: function () {
    var _this = this;
    if(!_this.data.isCodeIng){
      if(_this.data.loginName == ""){
        wx.showToast({
          title: '请输入手机号',
          icon: 'none',
          duration: 2000
        })
        return false;
      }
      if (!(/^1[345789]\d{9}$/.test(_this.data.loginName))) {
        wx.showToast({
          title: '手机号码填写有误',
          icon: 'none',
          duration: 2000
        })
        return false
      }
        _this.setData({codeDisabled: true,});
        console.log('获取验证码')
      let time = 60;
      let timer = setInterval(function() {
           time--;
           _this.setData({
               codeTxt: '(' + time + 's)后再获取',
               isCodeIng: true,
           });
           if (time <= 0) {
               _this.setData({
                   codeTxt: '获取验证码',
                   isCodeIng: false,
                   codeDisabled: false,
               });
               clearInterval(timer);
           }
       }, 1000);
      _this.getPhoneCodeAjax(_this.data.loginName);
    }
  },
  getPhoneCodeAjax: function(phoneNum) {
    wx.request({
      url: cfg.requestURL +'/backend/agent/mobile/getSmsCode',
      data: {"mobile": phoneNum},
      method: 'GET',
      header: {'content-type': 'application/json'},
      success(res) {
          console.log('验证码发送成功！');
      }
    })
  },
  wxSubmit:function(e){
    let self = this;
    wx.login({
      success: function(res) {
        if (res.code) {
          // 获取用户基本信息
          wx.getUserInfo({
            success: function(resu) {
              let fromdata = {
                'nickname': resu.userInfo.nickName,
                'sex': resu.userInfo.gender,
                'avatarurl': resu.userInfo.avatarUrl,
                'code': res.code
              };
              // 发起请求
              wx.request({
                  url: cfg.requestURL + '/user/wx/login',  //???没有使用吧？
                data: fromdata,
                header: {
                  'content-type': 'application/json'
                },
                method: 'POST',
                dataType: 'json',
                success: function(res) {
                    //console.log(JSON.stringify(res.data));
                },
                fail: function(res) {
                    //console.log("登录失败："+res.errMsg)
                }
              })
            },
            fail: function(e) {
                //console.log("获取用户基本信息失败，失败原因："+e.errMsg);
            }
          })
        } else {
            //console.log('登录失败：'+res.errMsg);
        }
      },
      fail: function(e) {
          //console.log('登录失败，失败原因：'+e.errMsg);
      }
    })
    // wx.getSetting({
    //   success(res) {
    //     if (res.authSetting['scope.userInfo']) {
    //       // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          
    //       console.log(e.detail.errMsg);
    //       console.log(e.detail.iv);
    //       console.log(e.detail.encryptedData);

    //       wx.getUserInfo({
    //         success: function(res) {
    //           console.log(res.userInfo)
    //         }
    //       })
    //     }
    //   }
    // })
  },
  loginSubmit:function(){
    var _this = this;
    if(_this.data.loginName == ""){
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (_this.data.loginPsd == "" && _this.data.loginType == 2) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (_this.data.loginCode == "" && _this.data.loginType == 1) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if(_this.data.loginCode == "" &&_this.data.loginType == 2){
      wx.showToast({
        title: '请输入验证码',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    wx.showLoading({
      title: '加载中...',
    })
    var loginData = '';
    if (_this.data.loginType == 1) {
      loginData = {
        "username": _this.data.loginName,
        "verifyCode": _this.data.loginCode,
        "key": this.data.codeDate,
        "loginType":_this.data.loginType
      }
    } else {
      loginData = {
        "username": _this.data.loginName,
        "password": utilMd5.hexMD5(_this.data.loginPsd),
        "key": this.data.codeDate,
        "verifyCode": _this.data.loginCode,
        "loginType":_this.data.loginType
      }
    }
    wx.request({
      url: cfg.requestURL +'/backend/agent/mobile/login', //仅为示例，并非真实的接口地址
      data: loginData,
      method:'POST',
      header: {
        "Content-Type": "application/json"
      },
      success(res) {
        wx.hideLoading();
        if (res.data.flag){
          wx.setStorageSync("agentId", res.data.data.agentId);
          wx.setStorageSync("token", res.data.data.token);
          wx.setStorageSync("userId", res.data.data.userId);
          wx.setStorageSync("authorityName", res.data.data.authorityName);
          wx.setStorageSync("loginName", res.data.data.loginName);
          wx.setStorageSync("agentType", res.data.data.agentType);
          _this.getSellerId();

          _this.goPages();

        }else{
          if (res.data.msg == '用户不存在'){
            wx.navigateTo({
              url: '../register/register'
            })
            return false;
          }
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  }, 
  getSellerId: function () {
    var _this = this;
    var Url = '';
    if (wx.getStorageSync('authorityName') == 'SELLER_USER') {
      Url = '/backend/seller/mobile/getSellerByloginId';
    }
    if ((wx.getStorageSync('authorityName') == 'PERSON_USER')) {
      Url = '/backend/person/mobile/getPersonByloginId'
    }
    wx.request({
      url: cfg.requestURL + Url + '?token=' + wx.getStorageSync('token') + '&loginId=' + wx.getStorageSync('userId'), //仅为示例，并非真实的接口地址
      method: 'GET',
      data: {},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        wx.hideLoading();
        if (res.data.flag) {
          if (wx.getStorageSync('authorityName') == 'SELLER_USER') {
            wx.setStorageSync("sellerId", res.data.data.sellerId);
            wx.setStorageSync("sellerCompanyName", res.data.data.sellerCompanyName);
            wx.setStorageSync("isAuthentication", res.data.data.isAuthentication);
          }
          if ((wx.getStorageSync('authorityName') == 'PERSON_USER')) {
            wx.setStorageSync("personId", res.data.data.personId);
            wx.setStorageSync("cardStatus", res.data.data.cardStatus);
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            mask: true,
            duration: 1500
          })
        }
      }
    })
  },
  // 登录成功后，跳转页面，如果是从其他页面过来的，跳转回其他页面，否则跳转到首页
  goPages:function(){
    var _exprs = wx.getStorageSync("noLoginInfoSv") || [];
      //console.log("_exprs=login===v" , _exprs);
    var _userSta = wx.getStorageSync("authorityName");
    if ((_userSta == 'PERSON_USER' && _exprs[0] == 'pages/itemList/itemList') || (_userSta == 'SELLER_USER' && _exprs[0] == 'pages/postProject/postProject') || (_userSta == 'SELLER_USER' && _exprs[0] == 'pages/invoicing/invoicing') || (_userSta == 'PERSON_USER' && _exprs[0] == 'pages/invoicing/invoicing')||(_userSta == 'PERSON_USER' && _exprs[1] == 'itemDetail')) {
      wx.redirectTo({
        url: '/' + _exprs[0],
      })
    } else {
      wx.redirectTo({
        url: '../index/index',
      })
    }
  },
  // 切换登录类型，1 为手机快捷登录，2 为账号密码登录
  changeLoginType: function(e) {
    this.setData({
      loginType: e.currentTarget.dataset.key,
      loginCode:''
    })
  }, 
  changeName:function(e){
    this.setData({
      loginName: e.detail.value
    })
  },
  changePsd: function (e) {
    this.setData({
      loginPsd: e.detail.value
    })
  },
  changeCode:function(e){
    this.setData({
      loginCode: e.detail.value
    })
  },
  forget:function(){
    wx.navigateTo({
      url: '../forget/forget'
    })
  },
  register:function(){
    wx.navigateTo({
      url: '../register/register'
    })
  },
  agreement: function () {
    wx.navigateTo({
      url: '../agreement/agreement'
    })
  },
  getCode:function(){
    var date = new Date().getTime();
    this.setData({
      codeDate: date,
      codeIcon: cfg.requestURL + "/backend/agent/mobile/getVerifyCodeImage?key=" + date
    })
    console.log(date, this.data.codeDate)
  },
  testCode:function(){
    var _this = this;
    wx.request({
      url: cfg.requestURL + '/testSessionId', //仅为示例，并非真实的接口地址
      data: {},
      method: 'GET',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success(res) {
          //console.log(res)
      }
    })
  }
})
